import { Component, OnInit, ViewChild } from '@angular/core';
import 'rxjs/add/operator/map';
import { CommService } from '../../comm/comm.service';
import { ReportUrls } from '../../comm/report.urls.conf';
import { SubArea } from '../../model/report/sub-area';
import { QueryModel } from '../../model/report/query-model';
import 'rxjs/add/operator/toPromise';
declare const $: any;
import { TVResource } from 'app/ptpmc/model/comm/tv-resource';
import { DxDropDownBoxComponent } from 'devextreme-angular';

@Component({
    selector: 'app-report-hourlydowntime',
    templateUrl: './hourlydowntime.component.html',
    styleUrls: ['./hourlydowntime.component.scss']
})

export class HourlydowntimeComponent implements OnInit {
    title = '小时停机报表及柱状图';
    // 查询数据
    // 产线
    public subAreaItems: SubArea[];
    public subAareSelected: any;
    // 设备、工位
    public equipemntItems: TVResource[] = [];
    public equipmentSelected: TVResource[];
    @ViewChild('dddb') dddb: DxDropDownBoxComponent;
    // 班次
    public shiftItems: any[];
    public shiftSelected: any;
    // 设备数据
    colData: any[] = [];
    // 选中tab
    barSelected = true;
    // 图例配置
    legendConfig: any[];
    legendConfig2: any[];
    // charts 数据
    chartOption1_bar: any;
    chartOption1_line: any;
    chartOption2_bar: any;
    chartOption2_line: any;
    constructor(private commServices: CommService) {
    }
    // 组件初始化
    ngOnInit() {
      // 初始化查询数据
      this.commServices.initDatePicker($('#DateTimeRange'), 'YYYY-MM-DD');
      this.subAreaItems = this.commServices.getSubAreas();
      this.subAareSelected = this.subAreaItems[0];
      this.equipemntItems = this.commServices.getTVResourceBySubArea(this.subAreaItems[0].subArea);
      this.equipmentSelected = this.equipemntItems;
      this.shiftItems = this.commServices.shifts;
      this.shiftSelected = this.shiftItems[0];
      // echarts 图例配置
      this.legendConfig = [
        { code: 'blkH0Tot', color: '#E87C25', text: '堵料' },
        { code: 'ovrH0Tot', color: '#C1232B', text: '循环超时' },
        { code: 'stvH0Tot', color: '#FE8463', text: '待料' },
        { code: 'dntH0Tot', color: '#FF4500', text: '停机' }
      ];
      this.legendConfig2 = [
        { codeList: [ 'blkH1Tot', 'blkH2Tot', 'blkH3Tot', 'blkH4Tot', 'blkH5Tot', 'blkH6Tot', 'blkH7Tot', 'blkH8Tot', 'blkH9Tot',
          'blkH10Tot', 'blkH11Tot', 'blkH12Tot' ], color: '#E87C25', text: '堵料' },
        { codeList: [ 'ovrH1Tot', 'ovrH2Tot', 'ovrH3Tot', 'ovrH4Tot', 'ovrH5Tot', 'ovrH6Tot', 'ovrH7Tot', 'ovrH8Tot', 'ovrH9Tot',
        'ovrH10Tot', 'ovrH11Tot', 'ovrH12Tot' ], color: '#C1232B', text: '循环超时' },
        { codeList: [ 'stvH1Tot', 'stvH2Tot', 'stvH3Tot', 'stvH4Tot', 'stvH5Tot', 'stvH6Tot', 'stvH7Tot', 'stvH8Tot', 'stvH9Tot',
        'stvH10Tot', 'stvH11Tot', 'stvH12Tot' ], color: '#FE8463', text: '待料' },
        { codeList: [ 'dntH1Tot', 'dntH2Tot', 'dntH3Tot', 'dntH4Tot', 'dntH5Tot', 'dntH6Tot', 'dntH7Tot', 'dntH8Tot', 'dntH9Tot',
        'dntH10Tot', 'dntH11Tot', 'dntH12Tot' ], color: '#FF4500', text: '停机' }
      ];
      // 获取设备数据, 加载echarts
      this.getEquipmentData();
    }
    // 清空设备选中项
    clearEquipmentSelected() {
      this.equipmentSelected = [];
    }
    // 选中设备
    equipmentSelectedOk() {
      this.dddb.instance.close();
    }
    // 选中产线，获取设备数据
    onSubAreaSelectedChange(subArea: any): void {
      this.equipemntItems = this.commServices.getTVResourceBySubArea(subArea.value.subArea);
      this.equipmentSelected = this.equipemntItems;
    }
    // 获取时间
    getTime(id: any): String {
      const timerange: String = $('#' + id).val();
      return timerange;
    }
    tabSelect(index: number) {
      if (index === 1) {
        this.barSelected = true;
      } else {
        this.barSelected = false;
      }
    }
    /**
     * 获取设备数据
     */
    getEquipmentData(): void {
        const queryModel: QueryModel = new QueryModel();
        queryModel.dateTimeRange = this.getTime('DateTimeRange');
        // queryModel.querySubAreaIds = [this.subAareSelected.subArea];
        // queryModel.queryResourceIds = this.equipmentSelected.map(e => e.resource);
        // queryModel.shift = this.shiftSelected.shiftId;
        queryModel.querySubAreaIds = ['C5BL1'];
        this.commServices
            .getList(queryModel, ReportUrls.HourlyDowntime)
            .subscribe(model => {
                if (model.resultCode === 200) {
                    console.log('model', model);
                    if (model.data) {
                      this.colData = model.data;
                      // 格式化chart1数据，按工位统计
                      const legend = this.legendConfig.map(a => a.text);
                      const xAxis = this.colData.map(a => a.equipment.replace(/[\W_]+/g, ''));
                      const series_bar = [];
                      const series_line = [];
                      for (const i of this.legendConfig) {
                        const serie_bar = {
                          name: i.text,
                          type: 'bar',
                          stack: 'Ad',
                          data: this.colData.map(a => a[i.code]),
                          itemStyle : { normal: {label : {show: true}}}
                        };
                        const serie_line = {
                          name: i.text,
                          type: 'line',
                          data: this.colData.map(a => a[i.code]),
                          // itemStyle : { normal: {label : {show: true}}}
                        };
                        series_bar.push(serie_bar);
                        series_line.push(serie_line);
                      }
                      this.chartOption1_bar = this.setOptions(legend, xAxis, series_bar, '故障统计(工位维度)');
                      this.chartOption1_line = this.setOptions(legend, xAxis, series_line, '故障统计(工位维度)');
                      // 格式化chart2数据，按小时统计
                      const legend2 = this.legendConfig.map(a => a.text);
                      const xAxis2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
                      // 格式化series数据
                      const forArr = this.colData.concat([]);
                      const baseData = forArr.shift();
                      let codeList = [];
                      for (const i of this.legendConfig2) {
                        codeList = codeList.concat(i.codeList);
                      }
                      // console.log('codeList', codeList);
                      // 合计小时数据
                      for (const i of forArr) {
                        for (const key in baseData) {
                          if (Object.prototype.hasOwnProperty.call(baseData, key)) {
                            if (codeList.includes(key)) {
                              baseData[key] += i[key];
                            }
                          }
                        }
                      }
                      // console.log('baseData', baseData);
                      const series2_bar = [];
                      const series2_line = [];
                      for (const i of this.legendConfig2) {
                        codeList = codeList.concat(i.codeList);
                        const data = [];
                        for (const j of i.codeList) {
                          data.push(baseData[j]);
                        }
                        const serie_bar = {
                          name: i.text,
                          type: 'bar',
                          stack: 'Ad',
                          data: data,
                          itemStyle : { normal: {label : {show: true}}}
                        };
                        const serie_line = {
                          name: i.text,
                          type: 'line',
                          data: data,
                          // itemStyle : { normal: {label : {show: true}}}
                        };
                        series2_bar.push(serie_bar);
                        series2_line.push(serie_line);
                      }
                      this.chartOption2_bar = this.setOptions(legend2, xAxis2, series2_bar, '故障统计(时间维度)');
                      this.chartOption2_line = this.setOptions(legend2, xAxis2, series2_line, '故障统计(时间维度)');
                    } else {
                      this.colData = [];
                      this.chartOption1_bar = null;
                      this.chartOption2_bar = null;
                    }
                    // console.log('this.colData', this.colData);
                    // this.colWidth = this.colData.length > 0 ? 100 / this.colData.length + '%' : '100%';
                    // console.log(this.colWidth);
                } else {
                    console.log(model.resultCode + ',' + model.resultMessage);
                }
            });
    }
    // 格式化设备名称
    formatEquipmentName(equipmentName) {
      // alert(equipmentName.split('').join(','));
      return equipmentName.replace(/[\W_]+/g, '');
    }
    setOptions(legend, xAxis, series, title) {
      return {
        title: {
            text: title
        },
        color: this.legendConfig.map(a => a.color),
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: legend
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        // toolbox: {
        //     feature: {
        //         saveAsImage: {}
        //     }
        // },
        xAxis: {
            type: 'category',
            // boundaryGap: false,
            data: xAxis
        },
        yAxis: {
            type: 'value'
        },
        series: series
      };
    }
}
